# settings_tab.py
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton
from PyQt6.QtCore import Qt
from db.AutoConfigDB import add_config, get_config


class SettingsTab(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # 主布局
        main_layout = QVBoxLayout()

        # 创建表单区域布局
        form_layout = QVBoxLayout()

        # 地址输入
        address_layout = QHBoxLayout()
        address_label = QLabel("地址:")
        self.address_input = QLineEdit()
        address_layout.addWidget(address_label)
        address_layout.addWidget(self.address_input)
        form_layout.addLayout(address_layout)

        # 秘钥输入
        key_layout = QHBoxLayout()
        key_label = QLabel("秘钥:")
        self.key_input = QLineEdit()
        key_layout.addWidget(key_label)
        key_layout.addWidget(self.key_input)
        form_layout.addLayout(key_layout)

        # 模型输入
        model_layout = QHBoxLayout()
        model_label = QLabel("模型:")
        self.model_input = QLineEdit()
        model_layout.addWidget(model_label)
        model_layout.addWidget(self.model_input)
        form_layout.addLayout(model_layout)

        # 设置表单区域的间距
        form_layout.setSpacing(10)

        # 将表单区域添加到主布局顶部
        main_layout.addLayout(form_layout)

        # 添加按钮布局
        button_layout = QHBoxLayout()
        button_layout.addStretch()  # 添加弹性空间，将按钮推到右侧
        self.confirm_button = QPushButton("确定")
        self.confirm_button.clicked.connect(self.on_confirm_clicked)
        button_layout.addWidget(self.confirm_button)
        main_layout.addLayout(button_layout)

        # 添加弹性空间，将内容推到顶部
        main_layout.addStretch()

        # 设置主布局的边距
        main_layout.setContentsMargins(30, 30, 30, 30)

        self.setLayout(main_layout)
        self.init_inputs()

    def init_inputs(self):
        address = get_config("llm_base_url")
        key = get_config("llm_api_key")
        model = get_config("llm_model")
        self.address_input.setText(address)
        self.key_input.setText(key)
        self.model_input.setText(model)

    def on_confirm_clicked(self):
        # 获取三个输入框的信息
        address = self.address_input.text()
        key = self.key_input.text()
        model = self.model_input.text()

        # 打印获取到的信息（你可以根据需要修改这里的处理逻辑）
        # https://dashscope.aliyuncs.com/compatible-mode/v1
        # sk-b23***427
        # qwen-plus
        add_config("llm_base_url", address)
        add_config("llm_api_key", key)
        add_config("llm_model", model)
        print(f"地址: {address}")
        print(f"秘钥: {key}")
        print(f"模型: {model}")

        # 这里可以添加保存设置或其他操作
        # 例如：
        # self.save_settings(address, key, model)